from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
#导入类视图
from django.views import View

from myapp.models import User
import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
#导入加密库
import hashlib
#导入图片库
#绘画库
from PIL import ImageDraw
#字体库
from PIL import ImageFont
#图片库
from PIL import Image
#随机库
import random
#文件流
import io

import requests

#导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os

#导入原生sql模块
from django.db import connection

import jwt

#导入redis数据库
import redis

#导入时间模块
import time

#导入公共目录变量
from mydjango.settings import BASE_DIR

#导包
from django.db.models import Q,F

#导入dwebsocket的库
from dwebsocket.decorators import accept_websocket


from myapp.models import User

#导包
import redis  

#定义ip和端口
host = "localhost"
port = 6379

#建立链接
r = redis.Redis(host=host,port=port)

#又拍云存储
import upyun
class Upyun(APIView):
    def post(self,request):
        #获取文件
        file = request.FILES.get('file')
        #新建又拍云实例
        up = upyun.UpYun('img1907','mama','FsC7GldRtyZIwWdnMCprBZvj7TI4Hnat')
        #声明头部信息
        headers = {'x-gmkerl-rotate':'auto'}
        #上传图片
        for chunk in file.chunks():
            res = up.put('./youpun.jpg',chunk,checksum=True,headers=headers)
        return Response({'filename':file.name})
        


class UploadFile(View):

	def post(self,request):

		#接收参数
		img = request.FILES.get("file")

		#建立文件流对象
		f = open(os.path.join(UPLOAD_ROOT,'',img.name),'wb')

		#写入服务器端
		for chunk in img.chunks():
			f.write(chunk)
		f.close()

		#返回文件名
		return HttpResponse(json.dumps({'filename':img.name},ensure_ascii=False),content_type='application/json')






import uuid
import time
import hmac
import base64
from hashlib import sha256
import urllib
import json



#构造钉钉回调方法
def ding_back(request):

    #获取code
    code = request.GET.get("code")

    t = time.time()
    #时间戳
    timestamp = str((int(round(t * 1000))))
    appSecret ='ly-AzMKMmCKQP3geaILT_An32kEfKO3HeOtApy5CgKwjytevVZC0WYsT2gxMB160'
    #构造签名
    signature = base64.b64encode(hmac.new(appSecret.encode('utf-8'),timestamp.encode('utf-8'), digestmod=sha256).digest())
    #请求接口，换取钉钉用户名
    payload = {'tmp_auth_code':code}
    headers = {'Content-Type': 'application/json'}
    res = requests.post('https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature='+urllib.parse.quote(signature.decode("utf-8"))+"&timestamp="+timestamp+"&accessKey=dingoaukgkwqknzjvamdqh",data=json.dumps(payload),headers=headers)

    res_dict = json.loads(res.text)
    # res_dict1 = eval(res_dict)
    print(res_dict)
    x = len(res_dict)
    print(x)
    #取出nick的值
    print(res_dict['user_info']['nick'])

    #判断是否用钉钉登录过
    dingding = User.objects.filter(username=str(res_dict['user_info']['nick'])).first()

    dingding_id = ""
    use_id = ""

    if dingding:
        #代表曾经登录过
        dingding_id = dingding.username
        use_id = dingding.id

    else:
        #自动创建账号 入库操作
        dingding = User(username=str(res_dict['user_info']['nick']),password="",type=0)

        #保存
        dingding.save()

        #查询用户id
        dingding = User.objects.filter(username=str(res_dict['user_info']['nick'])).first()

        dingding_id = str(res_dict['user_info']['nick'])
        use_id = dingding.id
    


    #将返回的数据进行解码
  
    return redirect('http://localhost:8080?dingding_id='+str(dingding_id)+"&uid="+str(use_id)) 


#新浪微博回调
def wb_back(request):

	 #获取code
    code = request.GET.get('code')

    #换取网址
    access_token_url = "https://api.weibo.com/oauth2/access_token"

    #发送请求进行换取
    res = requests.post(
        access_token_url,
        data={
            "client_id": '1837903328',
            "client_secret": "e744550929f2f5182aad8fd2cc897de6",
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": "http://127.0.0.1:8000/md_admin/weibo"
        }
    )

    #转换类型
    res = json.loads(res.text)

    #换取新浪微博昵称 json
    result = requests.get("https://api.weibo.com/2/users/show.json",params={'access_token':res['access_token'],'uid':res['uid']})

    print(result.text)

    result = json.loads(result.text)

    

    #判断该用户是否曾经登录过
    user = User.objects.filter(username=str(result['name'])).first()

    sina_id = ""
    user_id = ""

    if user: 
        sina_id = user.username
        user_id = user.id
    else:
        #手动创建账号
        user = User(username=str(result['name']),password="",img='',type=0)
        user.save()

        sina_id = result['name']
        #查询一下刚刚入库的新账号
        user = User.objects.filter(username=str(result['name'])).first()
        user_id = user.id




    # return HttpResponse(result['name'])

    # #进行跳转
    return redirect('http://localhost:8080?sina_id='+sina_id+"&uid="+str(user_id))

#自定义图片验证码
class MyCode(View):

    #定义rgb随机颜色
    def get_random_color(self):

        R = random.randrange(255)
        G = random.randrange(255)
        B = random.randrange(255)

        return (R,G,B)
    
    #定义图片视图
    def get(self,request):
        #画布
        img_size = (120,50)
        #定义图片对象
        image = Image.new('RGB',img_size,'white')
        #定义画笔
        draw = ImageDraw.Draw(image,'RGB')
        source = 'djahfjkdyuebfud123f'
        #接收容器
        code_str = ''
        #进入循坏禁止
        for i in range(4):
            #获取字母颜色
            text_color = self.get_random_color()
            #获取随机下标
            tmp_num = random.randrange(len(source))
            #随机字符串
            random_str = source[tmp_num]
            #装入容器中
            code_str +=random_str
            #绘制字符串
            draw.text((10+30*i,20),random_str,text_color)
        #获取缓存区
        buf = io.BytesIO()
        #将临时图片保存到地址中
        image.save(buf,'png')
        r.set('code',code_str)
        print(r.get('code'))

        return HttpResponse(buf.getvalue(),'image/png')



#MD5 加密方法
def make_password(mypass):
    md5 = hashlib.md5()

    #转码操作
    mypass_utf8 = str(mypass).encode(encoding="utf-8")

    #加密操作
    md5.update(mypass_utf8)

    #返回密文
    return md5.hexdigest()
   

class Register(APIView):
    def get(self,request):
        username = request.GET.get('username',None)
        password = request.GET.get('password',None)
        code = request.GET.get('code','mull')


        print(username)
        print(password)

        #获取验证码
        redis_code = r.get('code')
        redis_code = redis_code.decode('utf-8')
        print(redis_code)

        # 从session 中获取验证码
        session_code = request.session.get('code',None)
        print(session_code)
        # print(code,'*****')
        print("session:%s"%str(session_code))


        #判断验证码是否正确
        if code!= redis_code:
            res = {}
            res['code'] = 405
            res['message'] = '验证码输入错误'
            return Response(res)

        #排重操作
        user = User.objects.filter(username=username).first()

        if user:
            return Response({
                'code':403,
                'message':'该用户已经存在'
            })

        #入库
        user = User(username=username,password=make_password(password))

        user.save()

        return Response({'code':200,'message':'注册成功'})



#登录接口
class Login(APIView):
    def get(self,request):

        #接受参数
        username = request.GET.get('username',None)
        password = request.GET.get('password',None)

        #查询数据 百分之百查询用get
        user = User.objects.filter(username=username,password=make_password(password)).first()
        
        if user:

            return Response({'code':200,'message':"登录成功",'uid':user.id,
            'username':user.username})
            #这个user.id  user.username  对应的是localstorge.setItem()

        else:
            return Response({'code':403,'message':'您的用户名或者密码错误'})

